package com.huashi.dealer.modular.business.setting.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.huashi.dealer.commonEntity.Express;
import com.huashi.dealer.commonEntity.Goods;
import com.huashi.dealer.commonEntity.Setting;
import com.huashi.dealer.enums.DeliveryType;
import com.huashi.dealer.modular.business.express.service.ExpressService;
import com.huashi.dealer.modular.business.order.service.ExpressQueryService;
import com.huashi.dealer.modular.business.setting.mapper.SettingMapper;
import com.huashi.dealer.modular.business.setting.param.StoreSettingUpdateParam;
import com.huashi.dealer.modular.business.setting.param.TradeSettingUpdateParam;
import com.huashi.dealer.modular.business.setting.param.FullFreeSettingParam;
import com.huashi.dealer.modular.business.setting.service.StoreSettingService;
import com.huashi.dealer.modular.business.setting.vo.ExpressVo;
import com.huashi.dealer.modular.business.setting.vo.StoreSettingVo;
import com.huashi.dealer.modular.business.setting.vo.TradeSettingVo;
import com.huashi.dealer.modular.business.setting.vo.FullFreeSettingVo;
import com.huashi.dealer.modular.business.goods.mapper.GoodsMapper;
import com.huashi.dealer.modular.business.goods.mapper.GoodsImageMapper;
import com.huashi.dealer.modular.business.goods.vo.GoodsImageWithUrl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

@Service
public class StoreSettingServiceImpl extends ServiceImpl<SettingMapper,Setting> implements StoreSettingService {

    @Resource
    private SettingMapper settingMapper;
    @Resource
    private GoodsMapper goodsMapper;
    @Resource
    private GoodsImageMapper goodsImageMapper;
    @Resource
    private ExpressService expressService;

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public StoreSettingVo getStoreSetting() {
        Setting setting = settingMapper.getSetByKey("store");
        StoreSettingVo vo = new StoreSettingVo();
        if (setting == null || setting.getValues() == null) {
            return vo;
        }
        try {
            Map<String, Object> values = objectMapper.readValue(setting.getValues(), new TypeReference<Map<String, Object>>(){});
            Map<String, Object> store = (Map<String, Object>) values.getOrDefault("store", values);
            vo.setName((String) store.getOrDefault("name", ""));
            vo.setNewName((String) store.getOrDefault("new_name", ""));
            vo.setHotName((String) store.getOrDefault("hot_name", ""));
            Object delivery = store.get("delivery_type");
            List<Integer> deliveryTypes = new ArrayList<>();
            if (delivery instanceof List<?> list) {
                for (Object o : list) {
                    if (o instanceof Number n) deliveryTypes.add(n.intValue());
                    else if (o instanceof String s) deliveryTypes.add(Integer.parseInt(s));
                }
            }
            vo.setDeliveryType(deliveryTypes);

            Map<String, Object> kd100 = (Map<String, Object>) ((Map<String, Object>) store.getOrDefault("kuaidi100", new HashMap<>())) ;
            vo.setKuaidi100Customer((String) kd100.getOrDefault("customer", ""));
            vo.setKuaidi100Key((String) kd100.getOrDefault("key", ""));
        } catch (Exception ignored) {}
        return vo;
    }

    @Override
    public void updateStoreSetting(StoreSettingUpdateParam param) {
        // 校验配送方式至少选择一个
        if (param.getDeliveryType() == null || param.getDeliveryType().isEmpty()) {
            throw new IllegalArgumentException("配送方式至少选择一个");
        }
        // 校验枚举值
        for (Integer val : param.getDeliveryType()) {
            if (DeliveryType.getByValue(val) == null) {
                throw new IllegalArgumentException("非法的配送方式: " + val);
            }
        }

        Map<String, Object> store = new LinkedHashMap<>();
        store.put("name", param.getName());
        store.put("new_name", param.getNewName());
        store.put("hot_name", param.getHotName());
        store.put("delivery_type", param.getDeliveryType());
        Map<String, Object> kd100 = new LinkedHashMap<>();
        kd100.put("customer", param.getKuaidi100Customer());
        kd100.put("key", param.getKuaidi100Key());
        store.put("kuaidi100", kd100);

        String valuesJson;
        try {
            // PHP端值结构为 {"name":..., "delivery_type":[..], "kuaidi100":{...}} 或包裹在 store 键下
            valuesJson = objectMapper.writeValueAsString(store);
        } catch (Exception e) {
            throw new RuntimeException("序列化设置失败");
        }

        Setting setting = new Setting();
        setting.setKey("store");
        setting.setValues(valuesJson);
        setting.setDescribe("商城设置");
        settingMapper.upsert(setting);
    }

    @Override
    public TradeSettingVo getTradeSetting() {
        Setting setting = settingMapper.getSetByKey("trade");
        TradeSettingVo vo = new TradeSettingVo();
        if (setting == null || setting.getValues() == null) {
            return vo;
        }
        try {
            Map<String, Object> values = objectMapper.readValue(setting.getValues(), new TypeReference<Map<String, Object>>(){});
            Map<String, Object> trade = (Map<String, Object>) values.getOrDefault("trade", values);
            Map<String, Object> order = (Map<String, Object>) trade.getOrDefault("order", new HashMap<>());
            vo.setOrderCloseDays(toInt(order.get("close_days"), 0));
            vo.setOrderReceiveDays(toInt(order.get("receive_days"), 0));
            vo.setOrderRefundDays(toInt(order.get("refund_days"), 0));
            vo.setFreightRule(toInt(trade.get("freight_rule"), null));
        } catch (Exception ignored) {}
        return vo;
    }

    @Override
    public void updateTradeSetting(TradeSettingUpdateParam param) {
        Map<String, Object> order = new LinkedHashMap<>();
        order.put("close_days", param.getOrderCloseDays());
        order.put("receive_days", param.getOrderReceiveDays());
        order.put("refund_days", param.getOrderRefundDays());

        Map<String, Object> trade = new LinkedHashMap<>();
        trade.put("order", order);
        if (param.getFreightRule() != null) {
            trade.put("freight_rule", param.getFreightRule());
        }
        String valuesJson;
        try {
            valuesJson = objectMapper.writeValueAsString(trade);
        } catch (Exception e) {
            throw new RuntimeException("序列化设置失败");
        }
        Setting setting = new Setting();
        setting.setKey("trade");
        setting.setValues(valuesJson);
        setting.setDescribe("交易设置");
        settingMapper.upsert(setting);
    }

    @Override
    public FullFreeSettingVo getFullFreeSetting() {
        // 获取满额包邮设置
        Setting setting = settingMapper.getSetByKey("full_free");

        FullFreeSettingVo vo = new FullFreeSettingVo();
        
        if (setting != null && setting.getValues() != null) {
            try {
                ObjectMapper mapper = new ObjectMapper();
                JsonNode values = mapper.readTree(setting.getValues());
                
                vo.setIsOpen(values.path("is_open").asInt(0));
                vo.setIsGoodsType(values.path("is_goods_type").asInt(0));
                vo.setMoney(new BigDecimal(values.path("money").asText("0.01")));
                vo.setNumber(values.path("number").asInt(1));
                
                // 解析地区设置
                JsonNode notinRegion = values.path("notin_region");
                FullFreeSettingVo.NotInRegion region = new FullFreeSettingVo.NotInRegion();
                region.setProvince(mapper.convertValue(notinRegion.path("province"), new TypeReference<List<Long>>() {}));
                region.setCitys(mapper.convertValue(notinRegion.path("citys"), new TypeReference<List<Long>>() {}));
                region.setTreeData(mapper.convertValue(notinRegion.path("treeData"), new TypeReference<List<Object>>() {}));
                vo.setNotinRegion(region);
                
                // 解析不参与包邮的商品
                JsonNode notinGoods = values.path("notin_goods");
                List<Long> goodsIds = mapper.convertValue(notinGoods, new TypeReference<List<Long>>() {});
                
                if (goodsIds != null && !goodsIds.isEmpty()) {
                    List<FullFreeSettingVo.NotInGoods> goodsList = new ArrayList<>();
                    for (Long goodsId : goodsIds) {
                        // 查询商品基本信息
                        Goods goods = goodsMapper.selectById(goodsId);
                        if (goods != null) {
                            FullFreeSettingVo.NotInGoods notInGoods = new FullFreeSettingVo.NotInGoods();
                            notInGoods.setGoodsId(goodsId);
                            notInGoods.setGoodsName(goods.getGoodsName());
                            
                            // 查询商品图片
                            List<GoodsImageWithUrl> imageInfos = goodsImageMapper.getGoodsImageWithUrl(goodsId);
                            if (imageInfos != null && !imageInfos.isEmpty()) {
                                notInGoods.setImageUrl(imageInfos.get(0).getFileUrl());
                            }
                            
                            goodsList.add(notInGoods);
                        }
                    }
                    vo.setNotinGoods(goodsList);
                }
                
            } catch (Exception e) {
                // 如果解析失败，使用默认值
                vo.setIsOpen(0);
                vo.setIsGoodsType(0);
                vo.setMoney(new BigDecimal("0.01"));
                vo.setNumber(1);
                vo.setNotinRegion(new FullFreeSettingVo.NotInRegion());
                vo.setNotinGoods(new ArrayList<>());
            }
        } else {
            // 如果没有设置，使用默认值
            vo.setIsOpen(0);
            vo.setIsGoodsType(0);
            vo.setMoney(new BigDecimal("0.01"));
            vo.setNumber(1);
            vo.setNotinRegion(new FullFreeSettingVo.NotInRegion());
            vo.setNotinGoods(new ArrayList<>());
        }
        
        // TODO: 这里需要实现地区数据的获取
        // 暂时设置为空，后续需要实现Region相关的功能
        vo.setRegionData(new ArrayList<>());
        vo.setCityCount(0);
        
        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateFullFreeSetting(FullFreeSettingParam param) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            ObjectNode values = mapper.createObjectNode();
            
            values.put("is_open", param.getIsOpen());
            values.put("is_goods_type", param.getIsGoodsType());
            values.put("money", param.getMoney().toString());
            values.put("number", param.getNumber());
            
            // 设置地区信息
            ObjectNode notinRegion = mapper.createObjectNode();
            if (param.getNotinRegion() != null) {
                notinRegion.set("province", mapper.valueToTree(param.getNotinRegion().getProvince()));
                notinRegion.set("citys", mapper.valueToTree(param.getNotinRegion().getCitys()));
                notinRegion.set("treeData", mapper.valueToTree(param.getNotinRegion().getTreeData()));
            }
            values.set("notin_region", notinRegion);
            
            // 设置商品信息
            values.set("notin_goods", mapper.valueToTree(param.getNotinGoods()));
            
            // 保存到数据库
            Setting setting = settingMapper.getSetByKey("full_free");
            
            if (setting == null) {
                setting = new Setting();
                setting.setKey("full_free");
                setting.setDescribe("满额包邮设置");
                setting.setValues(values.toString());
                settingMapper.insert(setting);
            } else {
                setting.setValues(values.toString());
                settingMapper.upsert(setting);
            }
            
        } catch (Exception e) {
            throw new RuntimeException("保存满额包邮设置失败", e);
        }
    }

    private Integer toInt(Object val, Integer defaultVal) {
        if (val == null) return defaultVal;
        if (val instanceof Number n) return n.intValue();
        try { return Integer.parseInt(String.valueOf(val)); } catch (Exception e) { return defaultVal; }
    }
}


